import { Button, Card, Input, message, Popconfirm, Table } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import Ellipsis from '../../../components/Ellipsis';
import AddModal from './addModal';
import EditModal from './editModal';
import styles from './index.less';
import MaskText from '@/components/MaskText';

@connect(() => ({}))
export default class index extends PureComponent {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  state = {
    name: undefined,
    phone: undefined,
    addModalVisible: false,
    editModalVisible: false,
    editModalData: null,
    selectedRowKeys: [],
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
  };

  componentDidMount() {
    this.handleTableData();
  }

  handleTableData = () => {
    const { curPage, pageSize, name, phone } = this.state;
    this.setState({
      tableLoading: true,
    });
    let submitData = {
      curPage,
      pageSize,
      name,
      phone,
    };
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/deviceManagement/qualitypersonmanagement/page',
        ...submitData,
      },
      callback: response => {
        if (response && response.statusCode == '0' && response.data) {
          if (response.data.list.length === 0 && response.data.pageNum > 1) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableData();
              },
            );
          } else {
            this.setState({
              tableData: response.data.list,
              total: response.data.total,
              selectedRowKeys: [],
            });
          }
        } else {
          if (response.statusCode !== '0') {
            message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  handleSearch = () => {
    this.handleTableData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        name: undefined,
        phone: undefined,
      },
      () => {
        this.handleTableData();
      },
    );
  };

  handleEdit = record => {
    this.setState({
      editModalVisible: true,
      editModalData: record,
    });
  };

  changeEditModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    } else {
      this.setState({
        editModalVisible: false,
        editModalData: null,
      });
    }
  };

  handleDelete = record => {
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/deviceManagement/qualitypersonmanagement/delete',
        sid: record.sid,
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  handleAdd = () => {
    this.setState({
      addModalVisible: true,
    });
  };

  changeAddModalVisible = flag => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.handleTableData();
      this.setState({
        addModalVisible: false,
      });
    } else {
      this.setState({
        addModalVisible: false,
      });
    }
  };

  handleRowSelection = (selectedRowKeys, selectedRows) => {
    this.setState({
      selectedRowKeys: selectedRowKeys,
    });
  };

  handleBatchDelete = () => {
    const { selectedRowKeys } = this.state;
    this.props.dispatch({
      type: 'http/getDataWithRes',
      payload: {
        url: '/deviceManagement/qualitypersonmanagement/batch/delete',
        sids: selectedRowKeys.join(','),
      },
      callback: response => {
        if (response && response.statusCode == '0') {
          message.success('操作成功');
          this.handleTableData();
        } else {
          // message.error(response.statusMessage);
        }
      },
    });
  };

  render() {
    const {
      name,
      phone,
      addModalVisible,
      editModalVisible,
      editModalData,
      selectedRowKeys,
      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
    } = this.state;

    const {
      location: { pathname },
    } = this.props;

    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        render(val) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '电话',
        dataIndex: 'phone',
        render(val) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '描述',
        dataIndex: 'description',
        render: text => (
          <Ellipsis length={15} tooltip>
            {text}
          </Ellipsis>
        ),
      },
      { title: '创建时间', dataIndex: 'createDate' },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        fixed: 'right',
        align: 'center',
        render: (text, record) => {
          const btns = [];

          const editBtn = {
            title: '编辑',
            key: 'edit',
            auth: 'qualityPersonManagement_edit',
            onConfirm: () => this.handleEdit(record),
          };

          const deleteBtn = {
            title: '删除',
            key: 'delete',
            Popconfirm: true,
            message: '确认删除？',
            auth: 'qualityPersonManagement_delete',
            onConfirm: () => this.handleDelete(record),
          };

          btns.push(editBtn);
          btns.push(deleteBtn);
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };

    const tableProps = {
      columns,
      pagination,
      rowKey: 'sid',
      scroll: { x: 'max-content' },
      loading: tableLoading,
      dataSource: tableData,
      onChange: pagination => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableData();
          },
        );
      },
      rowSelection: {
        selectedRowKeys: selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.handleRowSelection(selectedRowKeys, selectedRows);
        },
      },
    };

    return (
      <div>
        <div className={styles.pateoSearch}>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>姓名:</div>
            <Input
              placeholder="请输入姓名"
              value={name}
              onChange={e => {
                this.setState({
                  name: e.target.value,
                });
              }}
            />
          </div>
          <div className={styles.searchInputStr}>
            <div className={styles.title}>电话:</div>
            <Input
              placeholder="请输入电话"
              value={phone}
              onChange={e => {
                this.setState({
                  phone: e.target.value,
                });
              }}
            />
          </div>

          <div className={styles.searchBtn}>
            <Button
              onClick={() => this.handleSearch()}
              type={'primary'}
              style={{ marginRight: '10px' }}
            >
              查询
            </Button>
            <Button onClick={() => this.handleReset()}>重置</Button>
          </div>
        </div>
        <div className={styles.pateoBtns}>
          {this.context.permissions.includes(pathname + '/qualityPersonManagement_add') ? (
            <div className={styles.btnItem}>
              <Button type="primary" onClick={() => this.handleAdd()}>
                新增
              </Button>
            </div>
          ) : null}
          {this.context.permissions.includes(pathname + '/qualityPersonManagement_delete') ? (
            <div className={styles.btnItem}>
              {selectedRowKeys.length > 0 ? (
                <Popconfirm
                  title="是否确认删除所选人员？"
                  onConfirm={() => this.handleBatchDelete()}
                >
                  <Button type="danger">批量删除</Button>
                </Popconfirm>
              ) : null}
            </div>
          ) : null}
        </div>
        <Card bordered={false} style={{ marginTop: 10 }}>
          <Table {...tableProps} />
        </Card>
        {addModalVisible ? (
          <AddModal orgList={[]} changeAddModalVisible={this.changeAddModalVisible} />
        ) : null}
        {editModalVisible ? (
          <EditModal
            editModalData={editModalData}
            changeEditModalVisible={this.changeEditModalVisible}
          />
        ) : null}
      </div>
    );
  }
}
